package com.ptu.spzx.security.Expection.handler;

import com.alibaba.fastjson.JSON;
import com.ptu.spzx.model.vo.common.Result;
import com.ptu.spzx.model.vo.common.ResultCodeEnum;
import com.ptu.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
        Result result=null;
        if(authException instanceof BadCredentialsException){
            result = Result.build(null, ResultCodeEnum.LOGIN_ERROR);
        } else if (authException instanceof InsufficientAuthenticationException) {
            result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }else{
            result = Result.build(authException.getMessage(), ResultCodeEnum.DATA_ERROR);
        }
        //响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
